/******************************
 * @Developer: many
 * @File: main.go
 * @Time: 2022/4/28 15:24
******************************/

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os/exec"
	"runtime"
	"strconv"
	"strings"
	"text/template"
	"time"
	"uptime/html"
	"uptime/lib"
)

var listener string

func init() {
	flag.StringVar(&listener, "port", ":8888", "http service port")
}

func main() {
	flag.Parse()

	// 获取主页面
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Access-Control-Allow-Origin", "*")
		if tml, err := template.New("index").Parse(html.IndexHtml); err == nil {
			if err = tml.Execute(writer, time.Now().Format("2006-01-02 15:04:05")); err != nil {
				log.Println(err)
				if _, err := writer.Write([]byte(`服务器错误`)); err != nil {
					log.Println(err)
				}
			}

			return
		} else {
			log.Println(err)
		}

		if _, err := writer.Write([]byte(`服务器错误`)); err != nil {
			log.Println(err)
		}
	})

	// 设置时间
	http.HandleFunc("/update", func(writer http.ResponseWriter, request *http.Request) {
		nt := request.URL.Query().Get("nt")
		if t, err := strconv.ParseInt(nt, 10, 64); err == nil {
			now := time.Unix(t, 0)
			if err = lib.UpdateSystemDateTime(&now); err != nil {
				log.Println(err)
				if _, err = writer.Write([]byte(`服务器错误`)); err != nil {
					log.Println(err)
				}
			}
			if _, err := writer.Write([]byte(`设置成功成功`)); err != nil {
				log.Println(err)
			}

			return
		}
		if _, err := writer.Write([]byte(`非法时间`)); err != nil {
			log.Println(err)
		}
	})

	// ntp 同步时间
	http.HandleFunc("/ntpdate", func(writer http.ResponseWriter, request *http.Request) {
		TM, err := lib.NtpDate()
		if err != nil {
			log.Println(err)
			if _, err = writer.Write([]byte(`服务器错误`)); err != nil {
				log.Println(err)
			}
			return
		}
		if err = lib.UpdateSystemDateTime(TM); err != nil {
			log.Println(err)
			if _, err = writer.Write([]byte(`服务器错误`)); err != nil {
				log.Println(err)
			}
			return
		} else {
			writer.Header().Set("Server-Now-Time", strconv.Itoa(int(time.Now().Unix())))
			if _, err := writer.Write([]byte(`同步成功`)); err != nil {
				log.Println(err)
			}
		}

	})

	go func() { // 打开本地浏览器
		if runtime.GOOS != "windows" {
			return
		}
		HostAndPort := strings.Split(listener, ":")
		log.Println("cmd", "start", fmt.Sprintf("http://127.0.0.1:%s", HostAndPort[1]))
		if err := exec.Command("cmd", "/c", "start", fmt.Sprintf("http://127.0.0.1:%s", HostAndPort[1])).Start(); err != nil {
			log.Println(err)
		}
	}()
	log.Fatal(http.ListenAndServe(listener, nil))
}
